import React, { Component } from 'react'
import Child from './Child'

class LifeTimes extends Component {
  state = {
    // title: ''
    color: 'red',
    list: [
      'abc',
      'def',
      'abc'
    ],

    width: '100px'
  }

  // 返回值要和state合并。如果返回值是null, 表示不合并
  static getDerivedStateFromProps(props, nextState) {
    return {
      title: nextState.title,
      msg: 'def'
    }
  }

  componentDidMount() {
    // setTimeout(() => {
    //   this.setState({
    //     title: 'hello'
    //   })
    // }, 2000)

    // setTimeout(() => {
    //   this.setState({
    //     color: 'red'
    //   })
    // }, 4000)
    

    // setTimeout(() => {
    //   this.forceUpdate()
    // }, 2000)
  }

  changeWidth = () => {
    this.setState({
      width: '200px'
    })
  }

  getSnapshotBeforeUpdate() {
    let square = document.querySelector('#square')
    let width = square.getBoundingClientRect().width
    return width
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(snapshot)
  }

  render() {
    return (
      <div>
        {/* {this.state.title} {this.state.msg} */}
        {/* <Child color={this.state.color}></Child> */}
        <Child list={this.state.list}></Child>

        <div id="square" style={{width: this.state.width, height: '100px', background: 'red'}}></div>

        <button onClick={this.changeWidth}>change width</button>
      </div>
    );
  }
}

export default LifeTimes;